package cn.wolfcode.shop.seckillserver.resolver;

import cn.wolfcode.shop.member.domain.User;
import cn.wolfcode.shop.member.util.CookieUtil;
import cn.wolfcode.shop.util.BaseKeyPrefix;
import cn.wolfcode.shop.redis.RedisService;
import cn.wolfcode.shop.seckillserver.anno.UserParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private RedisService redisService;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType() == User.class
                && methodParameter.hasParameterAnnotation(UserParam.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory)
            throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        String token = CookieUtil.getCookie(request,"token");
        if (token == null){
            return null;
        }

        BaseKeyPrefix keyprefix = new BaseKeyPrefix(1800, "USER_TOKEN:");

        User user = redisService.get(keyprefix, token, User.class);

        return user;
    }
}
